import React, { useState } from 'react'
import Taro, {  useDidShow, usePullDownRefresh, useReachBottom } from '@tarojs/taro'
import { request } from '@/utils'
import { View } from '@tarojs/components'
import { AtSearchBar, AtCard, AtButton } from 'taro-ui'
import './index.less'

const List = () => {
  const [list, setList] = useState([])
  const [value, setValue] = useState('')
  const [page, setPage] = useState(1)
  const [total, setTotal] = useState(0)
  const handleChange = (e) => {
    setValue(e)
  }
  const handleActionClick = () => {
    setPage(1)
    getList(value, 1)
  }
  const getList = async (name, index, flag) => {
    Taro.showLoading({mask: true})
    const res = await request({ url: `hkshihua/user/motorcade/getMotorcadeList?motorcadeName=${name || value}`, data: {pageIndex: index || page}})
    setList(flag ? [...list, ...res.list] : [...res.list])
    setTotal(res.total)
  }
  useDidShow(() => {
    setPage(1)
    getList(value, 1)
  })
  usePullDownRefresh(() => {
    setValue('')
    setPage(1)
    getList('', 1)
    Taro.stopPullDownRefresh()
  })
  useReachBottom(() => {
    if(page * 10 >= total) return
    setPage(page + 1)
    getList(value, page + 1, true)
  })
  const handleEdit = (item) => {
    const { name, account, userId } = item
    Taro.navigateTo({
      url: `/pages/fleetList/FleetEdit/index?name=${name}&account=${account}&userId=${userId}`
    })
  }
  const handleAdd = () => {
    Taro.navigateTo({
      url: '/pages/fleetList/FleetEdit/index'
    })
  }
  return (
    <View>
      <AtSearchBar
        showActionButton
        placeholder='请输入车队名称'
        value={value}
        onChange={handleChange}
        onActionClick={handleActionClick}
      />
      <View className='fleet-list'>
        {
          list.map((item) => {
            return item.role !== 'ADMINISTRATOR' &&  <View className='fleet-list_item' key={item.userId} >
            <AtCard
              title={item.name}
              thumb='http://www.logoquan.com/upload/list/20180421/logoquan15259400209.PNG'
            >
            <View>
              <View className='at-row _body _view_6p'>
                <View className='at-col at-col-8 at-col--wrap _view_6p'>
                  <View className='_view_6p'>账号:{item.account}</View>
                  <View className='_view_6p'>剩余油量:{item.oilRemain}升</View>
                </View>
                <View className='at-col at-col-3 at-col--wrap'>
                  <View style=''>
                    <AtButton type='primary' size='small' onClick={() => handleEdit(item)}>编辑</AtButton>
                  </View>
                </View>
              </View>
            </View>
          </AtCard>
        </View>
          })
        }
        {page * 10 >= total && <View className='no-data'>暂无更多数据</View>}
      </View>
      <View style={{height: '90px'}}></View>
      <View className='add-more' onClick={handleAdd}>
        +
      </View>
    </View >


  )
}

export default List
